<template>
	<view>
		<view class="mian" v-if="!$status">
			<scroll-view scroll-y="true" :scroll-top="scroll_top" class="center">
				<view class="sender" v-for="(item, index) in list" :class="item.u_id == data.u_id ? 'right' : 'left'">
					<view class="img_view"><img @longpress="longtap(item)" class="img" :src="item.outimg" /></view>
					<view class="content">
						<view class="name">{{ item.name }}</view>
						<text v-if="item.itype == 'text'" :user-select="true" decode space="nbsp" class="cont_text" v-text="item.content"></text>
						<view class="image_view">
							<image v-if="item.itype == 'image'" @load="img_load" @click="$viewImg(item.content)" lazy-load mode="widthFix" class="image" :src="item.content"></image>
						</view>
					</view>
				</view>
			</scroll-view>
			<view class="input">
				<u-icon class="photo" name="photo" size="40" @click="select_img"></u-icon>
				<input type="text" :focus="focus" v-model="value" class="text" />
				<view @click="openSend" class="submit" :class="{ send: isSend }">发送</view>
			</view>
		</view>
		<view v-else>
			<u-collapse>
				<u-collapse-item :title="item.head" v-for="(item, index) in itemList" :key="index">{{ item.body }}</u-collapse-item>
			</u-collapse>
		</view>
	</view>
</template>

<script>
import { get_room_list, upload } from '@/api/index.js';
import { send_room_info } from '@/api/user.js';

export default {
	data() {
		return {
			itemList: [
				{
					head: '赏识在于角度的转换',
					body: '只要我们正确择取一个合适的参照物乃至稍降一格去看待他人，值得赏识的东西便会扑面而来',
					open: true
				},
				{
					head: '生活中不是缺少美，而是缺少发现美的眼睛',
					body: '学会欣赏，实际是一种积极生活的态度，是生活的调味品，会在欣赏中发现生活的美',
					open: false
				},
				{
					head: '周围一些不起眼的人、事、物，或许都隐藏着不同凡响的智慧',
					body: '但是据说雕刻大卫像所用的这块大理石，曾被多位雕刻家批评得一无是处，有些人认为这块大理石采凿得不好，有些人嫌它的纹路不够美',
					open: false
				}
			],
			share: {
				title: '在线聊天室',
				imageUrl: 'http://resources.wzhyt.cn/images/4k1.jpg'
			},
			list: [],
			data: {
				u_id: ''
			},
			value: '',
			index: 0,
			scroll_top: 1,
			socket: null,
			focus: false
		};
	},
	onHide() {},
	computed: {
		isSend() {
			return this.value.replace(/\s+/g, '').length >= 1 ? true : false;
		}
	},
	destroyed() {
		this.socket.close();
	},
	onUnload() {
		this.socket.close();
	},
	onLoad() {
		this.data = uni.getStorageSync('userInfo');
		this.getList();
		this.get_room_list();
	},
	onShow() {
		console.log('聊天室');
	},
	methods: {
		img_load(){
			this.$nextTick(() => {
				this.scroll_top = Date.now();
			});
		},
		select_img() {
			//选择图片上传
			uni.chooseImage({
				success: chooseImageRes => {
					const tempFilePaths = chooseImageRes.tempFilePaths;
					console.log(chooseImageRes);
					uni.showLoading({
						title: '上传图片中...'
					});
					uni.uploadFile({
						url: upload,
						filePath: tempFilePaths[0],
						name: 'file[]',
						success: file => {
							console.log(file);
							let res = JSON.parse(file.data);
							if (res.code == 200) {
								send_room_info({
									content: res.data,
									itype: 'image'
								}).then(result => {
									console.log(result, '聊天室发送图片');
									if (result.code == 200) {
										this.socket.send({
											data: JSON.stringify({
												...this.data,
												type: 'add',
												itype: 'image',
												content: res.data
											})
										});
										this.$nextTick(() => {
											this.scroll_top = Date.now();
										});
									} else {
										uni.showToast({
											title: '发送失败！',
											icon: 'error'
										});
									}
								});
							} else {
								uni.hideLoading();
								uni.showToast({
									title: '图片上传失败',
									icon: 'error'
								});
							}
						}
					});
				}
			});
		},
		longtap(e) {
			//长按头像@对方
			if (e.u_id != this.data.u_id) {
				this.value = this.value + '@' + e.name;
				this.focus = false;
				setTimeout(() => {
					this.focus = true;
				}, 0);
			}
		},
		get_room_list() {
			//获取聊天室历史聊天记录
			get_room_list().then(result => {
				console.log(result, '获取历史聊天记录');
				if (result.data) {
					result.data.forEach(item => {
						this.list.unshift(item);
					});
					this.$nextTick(() => {
						this.scroll_top = Date.now();
					});
				}
			});
		},
		getList() {
			this.openWebSocket();
		},
		openWebSocket(status = false) {
			var _this = this;
			if (this.$status) {
				return null;
			}
			/* if (!status) {
				uni.showLoading({
					title: '正在连接中...'
				});
			} else {
				uni.showLoading({
					title: '重新连接中...'
				});
			} */
			this.socket = uni.connectSocket({
				// url: 'ws://192.168.137.1:8080/',
				url: 'wss://q.wzhyt.cn:8899',
				complete: function(e) {}
			});
			this.socket.onOpen(function() {
				console.log('websocket已连接');
				console.log(status);
				if (!status) {
					//第一次进入
					this.index = 1;
					_this.socket.send({
						data: JSON.stringify({
							..._this.data, //发送用户的u_id
							type: 'new'
						})
					});
					/* uni.showToast({
						title: '成功进入聊天室'
					}); */
				} else {
					_this.socket.send({
						data: JSON.stringify({
							..._this.data, //发送用户的u_id
							type: 'reconnect' //重新连接
						})
					});
				}
				uni.hideLoading();
			});
			_this.socket.onMessage(function(data) {
				data = JSON.parse(data.data);
				_this.list.push(data);
				_this.$nextTick(() => {
					_this.scroll_top = Date.now();
				});
			});
			_this.socket.onClose(function(res) {
				uni.hideLoading();
				console.log('已断开', res);
				setTimeout(function() {
					_this.openWebSocket(true); //重新连接
				}, 500);
			});
			_this.socket.onError(function(err) {
				uni.hideLoading();
				console.log(err);
				setTimeout(function() {
					_this.openWebSocket(true); //重新连接
				}, 500);
			});
		},
		openSend() {
			//发送消息
			var _this = this;
			console.log(this.scroll_top);
			if (_this.value.replace(/\s+/g, '').length >= 1) {
				send_room_info({
					content: _this.value,
					itype: 'text'
				}).then(result => {
					console.log(result, '聊天室发送消息');
					if (result.code === 200) {
						_this.socket.send({
							data: JSON.stringify({
								...this.data,
								type: 'add',
								itype: 'text',
								content: this.value
							})
						});
						this.value = '';
						this.$nextTick(() => {
							this.scroll_top = Date.now();
						});
					} else {
						uni.showToast({
							title: '发送失败！',
							icon: 'error'
						});
					}
				});
			}
		}
	}
};
</script>
<style>
page {
	background-color: #f8f8f8;
}
</style>
<style lang="scss" scoped>
.mian {
	height: 100vh;
}
.center {
	height: calc(100vh - 100rpx);
	padding: 0 0 0;
	box-sizing: border-box;
}
.sender {
	display: flex;
	padding: 15rpx 30rpx 15rpx;
	.img_view {
		.img {
			width: 80rpx;
			height: 80rpx;
			border-radius: 10rpx;
		}
	}
	.content {
		.name {
			color: #333;
		}
		.image_view{
			padding: 15rpx 0;
			font-size: 0;
			.image{
				max-width: calc(100% - 60rpx);
				height: auto;
				border-radius: 8rpx;
				overflow: hidden;
			}
		}
		.cont_text {
			display: inline-block;
			max-width: 550rpx;
			font-size: 27.5rpx;
			margin-top: 8rpx;
			position: relative;
			background-color: #12b7f5;
			color: #fff;
			padding: 15rpx;
			border-radius: 18rpx;
			direction: initial;
		}
	}
	&.left {
		.img_view {
			padding: 0 30rpx 0 0;
		}
		.content {
			.cont_text {
				&::after {
					content: '';
					height: 0px;
					width: 0px;
					border-width: 20rpx;
					border-style: solid;
					border-color: transparent #12b7f5 transparent transparent;
					position: absolute;
					left: -30rpx;
					top: 10rpx;
				}
			}
		}
	}
	&.right {
		direction: rtl;
		.img_view {
			padding: 0 0 0 30rpx;
		}
		.name {
			text-align: right;
		}
		.content {
			.cont_text {
				text-align: left;
				&::after {
					content: '';
					height: 0px;
					width: 0px;
					border-width: 20rpx;
					border-style: solid;
					border-color: transparent transparent transparent #12b7f5;
					position: absolute;
					right: -30rpx;
					top: 10rpx;
				}
			}
		}
	}
}

.input {
	height: 100rpx;
	background-color: #ffffff;
	display: flex;
	position: fixed;
	left: 0;
	bottom: 0;
	right: 0;
	padding: 20rpx 20rpx;
	.photo {
		margin-right: 20rpx;
	}
}
.text {
	width: 85%;
	height: 100%;
	border: none;
	border-radius: 35rpx;
	background-color: #f8f8f8;
	padding: 0 20rpx;
}
.submit {
	height: 100%;
	border: none;
	line-height: 60rpx;
	background-color: #b1effe;
	border-radius: 30rpx;
	margin-left: 20rpx;
	color: #fff;
	font-size: 30rpx;
	padding: 0 25rpx;
	white-space: nowrap;
	&.send {
		background-color: #12b7f5;
	}
}
</style>
